package mqtt;

import org.eclipse.paho.mqttv5.client.IMqttToken;
import org.eclipse.paho.mqttv5.client.MqttCallback;
import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;

public class MQTTProducerUtils {
	
	private static MQTTv5Client mqttClient = null;
	
	private static void initMQTTClient() {
		mqttClient = new MQTTv5Client(new ProducerCallback(),"MQTTProducerUtils"+System.currentTimeMillis());
		try {
			mqttClient.connect();
		} catch (MqttException e) {
			mqttClient = null;
			e.printStackTrace();
		}
	}
	
	
	public static void producer(String topic,String msg,int qos) throws MqttException {
		if(null == mqttClient) {
			initMQTTClient();
		}
		mqttClient.publish(topic, msg, qos, false);
	}
	
	public static void main(String[] args) throws MqttException {
		MQTTProducerUtils.producer("cruise_action_topic","{\"sn\":\"CY05-SCOP-1801\",\"cruise_action\":\"S\"}",1);
	}

}

class ProducerCallback implements MqttCallback{

	@Override
	public void disconnected(MqttDisconnectResponse disconnectResponse) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mqttErrorOccurred(MqttException exception) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void messageArrived(String topic, MqttMessage message) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void deliveryComplete(IMqttToken token) {
		try {
			System.out.println("消息发送是否完成: " + token.isComplete());
	        
	        // 2. 关联的客户端
	        System.out.println("发起发送的客户端: " + token.getClient().getClientId());
	        
	        // 3. 消息特有的信息（IMqttDeliveryToken 专属）
	        MqttMessage message = token.getMessage();
	        System.out.println(message == null);
		} catch (MqttException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void connectComplete(boolean reconnect, String serverURI) {
		System.out.println("与MQTT服务端建立建立连接");
		
	}

	@Override
	public void authPacketArrived(int reasonCode, MqttProperties properties) {
		// TODO Auto-generated method stub
		
	}

}
